﻿using System;
using System.Collections.Generic;

using System.Text;
using System.Web;
using System.Web.UI.WebControls;
using System.Drawing;
using System.Drawing.Imaging;
using System.IO;


namespace lxwmvc
{
    /// <summary>
    /// 图像处理类
    /// </summary>
    public class imagehelper 
    {
        /// <summary>
        /// 把base64字符串转换成图片
        /// </summary>
        /// <param name="base64string"></param>
        /// <returns></returns>
        public static Bitmap GetImageFromBase64(string base64string)
        {
            byte[] b = Convert.FromBase64String(base64string);
            MemoryStream ms = new MemoryStream(b);
            Bitmap bitmap = new Bitmap(ms);
            return bitmap;
        }

        /// <summary>
        /// 把图片转换成base64字符串
        /// </summary>
        /// <param name="image"></param>
        /// <returns></returns>
        public static string GetBase64FromImage(System.Drawing.Image image)
        {
            string strbaser64 = "";
            try
            {
                MemoryStream ms = new MemoryStream();
                image.Save(ms, System.Drawing.Imaging.ImageFormat.Jpeg);
                byte[] arr = new byte[ms.Length];
                ms.Position = 0;
                ms.Read(arr, 0, (int)ms.Length);
                ms.Close();
                strbaser64 = Convert.ToBase64String(arr);
            }
            catch (Exception)
            {
                throw new Exception("Something wrong during convert!");
            }
            return strbaser64;
        }

        /// <summary>
        /// 默认切割
        /// <param name="bmp">图片</param>
        /// <param name="size">修建图片并等比例缩小，而且留白</param>
        /// </summary>
        public static Bitmap cutsuoxiaimage(Bitmap bmp, int[] size)
        {
            return cutsuoxiaimage(bmp, size, true,true);
        }

        /// <summary>
        /// 默认切割
        /// <param name="bmp">图片</param>
        /// <param name="size">修建图片并等比例缩小，而且留白</param>
        /// </summary>
        public static Bitmap cutsuoxiaimage(Bitmap bmp, Size size)
        {
            return cutsuoxiaimage(bmp, new int[] { size.Width, size.Height }, true,true);
        }

        /// <summary>
        /// 图片进行处理
        /// </summary>
        /// <param name="bmp">图片</param>
        /// <param name="size">缩小到什么尺寸</param>
        /// <param name="isCut">是否裁剪</param>
        /// <param name="isblank">不够的地方是否留白</param>
        /// <returns></returns>
        public static Bitmap cutsuoxiaimage(Bitmap bmp, int[] size, bool isCut, bool isblank)
        {
            System.Drawing.Image image = bmp.Clone() as System.Drawing.Image;

            if (isCut) image = imagecut(image, size);
            Bitmap m = (Bitmap)getminpic(image, size);

            //if (m.Width != size[0] || m.Height != size[1])
            //    return new Bitmap(m, size[0], size[1]);
            if (isblank)
            {
                Bitmap map = new Bitmap(size[0], size[1], m.PixelFormat);
                float x = (size[0] - m.Width) / 2f;
                float y = (size[1] - m.Height) / 2f;

                Graphics newBmpGraphics = Graphics.FromImage(map);
                newBmpGraphics.Clear(Color.White);
                newBmpGraphics.DrawImage(m,x,y);
                newBmpGraphics.Save();
                newBmpGraphics.Dispose();

                m = map;
            }

            return m;
        }

        /// <summary>
        /// 图片压缩
        /// </summary>
        /// <param name="iSource"></param>
        /// <param name="outPath"></param>
        /// <param name="flag"></param>
        /// <returns></returns>
        public static bool GetPicThumbnail(System.Drawing.Image iSource, string outPath, int flag)
        {
            ImageFormat tFormat = iSource.RawFormat;
            //以下代码为保存图片时，设置压缩质量  
            EncoderParameters ep = new EncoderParameters();
            long[] qy = new long[1];
            qy[0] = flag;//设置压缩的比例1-100  
            EncoderParameter eParam = new EncoderParameter(System.Drawing.Imaging.Encoder.Quality, qy);
            ep.Param[0] = eParam;
            try
            {
                ImageCodecInfo[] arrayICI = ImageCodecInfo.GetImageEncoders();
                ImageCodecInfo jpegICIinfo = null;
                for (int x = 0; x < arrayICI.Length; x++)
                {
                    if (arrayICI[x].FormatDescription.Equals("JPEG"))
                    {
                        jpegICIinfo = arrayICI[x];
                        break;
                    }
                }
                if (jpegICIinfo != null)
                {
                    iSource.Save(outPath, jpegICIinfo, ep);//dFile是压缩后的新路径  
                }
                else
                {
                    iSource.Save(outPath, tFormat);
                }
                return true;
            }
            catch
            {
                return false;
            }
            finally
            {
                iSource.Dispose();
                iSource.Dispose();
            }
        }

        /// <summary>
        /// 保存并返回根目录路径
        /// </summary>
        /// <param name="img">图片</param>
        /// <param name="path">保存到什么位置，相对网站路径</param>
        /// <returns></returns>
        public static string saveimage(System.Drawing.Image img, string path = "")
        {
            string strUrl = string.Concat(new object[] { "/Upload/img/", DateTime.Now.Year, "/", DateTime.Now.Month, "/", DateTime.Now.ToString("yyyyMMdd_HHmmss_ffff"), ".jpg" });
            
            //这里外部给出地址
            if (!string.IsNullOrEmpty(path)) strUrl = path;
            string strNewFilePath = HttpContext.Current.Server.MapPath(strUrl);
            Directory.CreateDirectory(Path.GetDirectoryName(strNewFilePath));
            img.Save(strNewFilePath, ImageFormat.Jpeg);

            return strUrl;
        }

        /// <summary>
        /// 直接裁剪图片形成缩略图
        /// </summary>
        /// <param name="bmp">图片</param>
        /// <param name="size">缩略图大小</param>
        /// <returns></returns>
        public static Bitmap cutimage(Bitmap bmp, int[] size)
        {
            System.Drawing.Image image = bmp.Clone() as System.Drawing.Image;

            image = imagecut(image, size);
            return (Bitmap)getminpic(image, size);
        }


        /// <summary>
        /// 图片切割
        /// </summary>
        /// <param name="image">图片</param>
        /// <param name="size">缩略图大小</param>
        /// <returns></returns>
        static System.Drawing.Image imagecut(System.Drawing.Image image, int[] size)
        {
            if (!checksize(image, size)) return image;

            double p = 0.00;
            Rectangle rect = new Rectangle(0, 0, 0, 0);

            if (image.Size.Height / (double)size[1] > image.Size.Width / (double)size[0])
            {
                p = image.Size.Width / (double)size[0];
                rect.Y = (int)Math.Floor((image.Size.Height - size[1] * p) / 2);

                rect.Width = image.Width;
                rect.Height = (int)Math.Floor(size[1] * p);
            }
            else
            {
                p = image.Size.Height / (double)size[1];
                rect.X = (int)Math.Floor((image.Size.Width - size[0] * p) / 2);

                rect.Height = image.Height;
                rect.Width = (int)Math.Floor(size[0] * p);
            }

            Bitmap newBmp = new Bitmap(rect.Width, rect.Height, image.PixelFormat);
            Graphics newBmpGraphics = Graphics.FromImage(newBmp);
            newBmpGraphics.DrawImage(image, new Rectangle(0, 0, rect.Width, rect.Height), rect, GraphicsUnit.Pixel);
            newBmpGraphics.Save();

            image.Dispose();

            return newBmp;
        }

        /// <summary>
        /// 生成小的图片
        /// </summary>
        /// <param name="MaxPic">图片</param>
        /// <param name="size">缩略图大小</param>
        /// <returns></returns>
        static private System.Drawing.Image getminpic(System.Drawing.Image MaxPic, int[] size)
        {
            int height = 0;
            int width = 0;
            if ((MaxPic.Height <= size[1]) && (MaxPic.Width <= size[0]))
            {
                height = MaxPic.Height;
                width = MaxPic.Width;
                goto End;
            }
            if (size[1] * MaxPic.Width == MaxPic.Height * size[0])
            {
                width = size[0];
                height = size[1];
                goto End;
            }
            else if (MaxPic.Height * size[0] < MaxPic.Width * size[1])
            {
                 width = size[0];
                height = (int)Math.Floor(MaxPic.Height / (MaxPic.Width / (double)size[0]));
                goto End;
            }
            else
            {
                width = (int)Math.Floor(MaxPic.Width / (MaxPic.Height / (double)size[1]));
                height = size[1];
                goto End;
            }

        End:
            {
                Bitmap newBmp = new Bitmap(width, height, MaxPic.PixelFormat);
                Graphics newBmpGraphics = Graphics.FromImage(newBmp);
                newBmpGraphics.DrawImage(MaxPic, new Rectangle(0, 0, width, height), new Rectangle(0, 0, MaxPic.Width, MaxPic.Height), GraphicsUnit.Pixel);
                newBmpGraphics.Save();
                newBmpGraphics.Dispose();
                return newBmp;

                //return MaxPic.GetThumbnailImage(width, height, null, new IntPtr());
            }
        }

        /// <summary>
        /// 检查图片是否满足裁剪要求
        /// </summary>
        /// <param name="img">图片</param>
        /// <param name="size">大小</param>
        /// <returns></returns>
        static private bool checksize(System.Drawing.Image img, int[] size)
        {
            return (img.Height > size[1] || img.Width > size[0]);
        }
    }
}
